<?php

class DProduct2 extends DActiveRecord {

    private $curPage = 0;
    private $defaultSort;
    public $params;
    public $file1, $file2;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function init() {
        //set parameter
        $this->params = Yii::app()->params['product_2'];
        $this->params['upload_dir'] = Yii::app()->params['upload_dir']
            . $this->params['basename'] . '/';
        $this->params['upload_url'] = Yii::app()->params['upload_url']
            . $this->params['basename'] . '/';
    }

    public function tableName() {
        return 'product2';
    }

    public function rules() {
        return array(
            array('project, type_id', 'required'),
            array('file1, file2', 'required', 'message' => Yii::t(
                'DadminModule.message', 'required_file', array(
                    '{0}' => 'Image',
                ))
            ),
            array('activated_flag', 'boolean'),
            array('project, career, country, link', 'length', 'max'=>255),
            array('id, files', 'safe'),
            array('project, type_id, activated_flag', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'rtype' => array(self::BELONGS_TO, 'NewsletterType', 'type_id'),
        );
    }

    public function attributeLabels() {
        return array(
            'id'             => 'ID',
            'project'        => 'Project',
            'career'         => 'Ngành nghề',
            'country'        => 'Địa điểm',
            'link'           => 'Liên kết',
            'files'          => 'Upload',
            'type_id'        => 'Category',
            'status'         => 'Status',
            'activated_flag' => 'Active',
            'sort_order'     => 'Sort Order',
        );
    }

    public function search() {
        //Restore state from session
        $this->restoreState();

        //Criteria
        $criteria       = new CDbCriteria;
        $this->setTableAlias('T');
        $criteria->with = array('rtype');

        $criteria->compare('type_id', $this->type_id);
        $criteria->compare('T.project', $this->project, true);
        $criteria->compare('T.career', $this->career, true);
        $criteria->compare('T.country', $this->country, true);
        $criteria->compare('T.activated_flag', $this->activated_flag);
        $criteria->compare('rtype.activated_flag', true);

        //Sorting
        $sort               = new CSort();
        $sort->defaultOrder = ($this->defaultSort == '')
            ?
            array('sort_order' => true) 
            :
            $this->defaultSort;
        
        $sort->attributes = array(
            'project' => array(
                'asc'     => 'T.project ASC',
                'desc'    => 'T.project DESC',
                'default' => 'asc',
            ),
            'country' => array(
                'asc'     => 'T.country ASC',
                'desc'    => 'T.country DESC',
                'default' => 'asc',
            ),
            'type_id' => array(
                'asc'            => 'rtype.title ASC, T.sort_order DESC',
                'desc'           => 'rtype.title DESC, T.sort_order DESC',
                'default'        => 'asc',
            ),
            'activated_flag' => array(
                'asc'        => 'T.activated_flag ASC, T.sort_order DESC',
                'desc'       => 'T.activated_flag DESC, T.sort_order DESC',
                'default'    => 'asc',
            ),
            'sort_order' => array(
                'asc'  => 'T.sort_order ASC',
                'desc' => 'T.sort_order DESC',
            ),
        );
        $sort->applyOrder($criteria);

        return new CActiveDataProvider($this, array(
            'criteria'   => $criteria,
            'sort'       => $sort,
            'pagination' => array('currentPage' => $this->curPage),
        ));
    }

    private function restoreState() {
        $state = SpsState::getState();

        if ($state) {
            if (isset($state['sort']))
                $this->defaultSort = $state['sort'];
            if (isset($state['page']))
                $this->curPage     = $state['page'];

            if (isset($state['search'])) {
                foreach ($state['search'] as $key => $value)
                    if ($value != '')
                        $this->$key = $value;
            }
        }
    }

    protected function beforeSave() {
        parent::beforeSave();
        $scenario = $this->getScenario();
        
        if ($scenario=='insert' || $scenario=='update') {
            if ($scenario == 'insert') {
                $this->setAttribute('sort_order', $this->getAutoIncrement($this->tableName()));

                //----- files -----
                $mySession = Yii::app()->user->getState($this->params['plupload_session']);
                $extSmall = MyHelpers::getInstance()->getExtString($mySession['small']['file_name']);
                $extNormal = MyHelpers::getInstance()->getExtString($mySession['normal']['file_name']);

                $uid = uniqid();
                $this->files  = implode(';', array(
                    $uid . '_n.' . $extNormal,
                    $uid . '_n_th.' . $extNormal,
                    $uid . '_s.' . $extSmall,
                ));
                //----- //files -----
            }
        }

        return true;
    }
    
    protected function afterSave() {
        $scenario = $this->getScenario();
        
        if ($scenario=='insert' || $scenario=='update') {
            //----- move file -----
            $mySession = Yii::app()->user->getState($this->params['plupload_session']);
            list($fNormal, $fNormalThumb, $fSmall) = explode(';', $this->files);
            $tempDir = Yii::app()->params['tempo_dir'];

            rename($tempDir . $mySession['normal']['file_name'],
                $this->params['upload_dir'] . $fNormal
            );
            rename($tempDir . $mySession['normal']['thumb_name'],
                $this->params['upload_dir'] . $fNormalThumb
            );
            rename($tempDir . $mySession['small']['file_name'],
                $this->params['upload_dir'] . $fSmall
            );
            //----- //move file -----

            //clear session
            $this->clearSession();
        }
        
        return true;
    }

    protected function beforeDelete() {
        parent::beforeDelete();
        $this->deleteFile($this->files);
        return true;
    }

    /*-------------------------------------------------------------------------
      PROCESSING FILE
     ------------------------------------------------------------------------*/
    private function deleteFile($sFiles) {
        $aFiles = explode(';', $sFiles);

        foreach ($aFiles as $file) {
            $path = $this->params['upload_dir'] . $file;
            if (is_file($path)) unlink($path);
        }
        
        return TRUE;
    }
    /*-------------------------------------------------------------------------
      //PROCESSING FILE
     ------------------------------------------------------------------------*/
    
    /*-------------------------------------------------------------------------
      AJAX SUPPORTS
     ------------------------------------------------------------------------*/
    /**
     * Lấy nội dung của một đề mục tương ứng trong bảng newsletter_content
     * @param mixed $type_id
     * @return CDataProvider
     */
    public function getCategory($type_id = '') {
        $criteria = new CDbCriteria();
        
        $criteria->compare('activated_flag', 1);
        
        if ($this->type_id != '')
            $type_id = $this->type_id;

        if (! empty($type_id)) {
            if ($type_id == 'default') {
                $criteria->compare('type_id', 1); //information
            } elseif (is_array($type_id)) {
                $criteria->addInCondition('type_id', $type_id);
            } else {
                $criteria->compare('type_id', $type_id);
            }
        }

        $criteria->compare('id', $this->id);
        $criteria->compare('title', $this->title, true);

        return new CActiveDataProvider($this, array(
                'criteria'   => $criteria,
                'sort'     => array(
                    'defaultOrder' => array('sort_order' => CSort::SORT_DESC)
                ),
            ));
    }
    /*-------------------------------------------------------------------------
      //AJAX SUPPORTS
     ------------------------------------------------------------------------*/
    
    /*-------------------------------------------------------------------------
      SORT HELPER
     ------------------------------------------------------------------------*/
    /**
     * Hoán đổi thuộc tính sort_order của 2 record có ID tương ứng
     * @param integer $pk1
     * @param integer $pk2 
     */
    public function swapSortOrder($pk1, $pk2) {
        //get values
        
        $record_1    = $this->findByPk($pk1);
        $record_1->setScenario('sort');
        $sortOrder_1 = $record_1->getAttribute('sort_order');

        $record_2    = $this->findByPk($pk2);
        $record_2->setScenario('sort');
        $sortOrder_2 = $record_2->getAttribute('sort_order');

        //update
        $record_1->sort_order = $sortOrder_2;
        $record_1->save(false);
        $error = $record_1->getErrors();

        $record_2->sort_order = $sortOrder_1;
        $record_2->save(false);
        $error = $record_2->getErrors();
    }

    /**
     * Lấy Record của trang liền sau
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetLesser($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage + 1) * $pageSize;
        $command->limit(1, $offset);
        $row    = $command->queryScalar($criteria->params);

        return $row;
    }

    /**
     * Lấy Record của trang liền trước
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetGreater($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage - 1) * $pageSize + ($pageSize - 1);
        $command->limit(1, $offset);
        $row = $command->queryRow(true, $criteria->params);

        return $row['id'];
    }

    /**
     * Đưa record có $pk1 lên đầu (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeTop($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
                'order' => 'sort_order ASC'
            ));
        $criteria->compare('sort_order', '>=' . $record1->sort_order);
        $criteria->compare('sort_order', '<=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;
            
            $row->sort_order = $updatedValue;
            $row->setScenario('sort');
            $row->save(false);

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Đưa record có $pk1 xuống dưới cùng (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeBottom($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
            'order' => 'sort_order DESC'
        ));
        $criteria->compare('sort_order', '<=' . $record1->sort_order);
        $criteria->compare('sort_order', '>=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->setScenario('sort');
            $row->save(false);
            $error = $row->getErrors();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Get data from $criteria into $command
     * @param type $criteria
     * @param type $command 
     */
    private function sortFillCommand($criteria, $command) {
        $command->select('T.id AS id')->from('product2 T');
        $command->leftJoin(
            'newsletter_type rtype', 'rtype.id = T.type_id'
        );

        if ($criteria->condition != '')
            $command->where($criteria->condition);
        if ($criteria->order != '')
            $command->order($criteria->order);
    }
    /*-------------------------------------------------------------------------
      //SORT HELPER
     ------------------------------------------------------------------------*/
    
    /*-------------------------------------------------------------------------
      VALIDATOR
     ------------------------------------------------------------------------*/
    public function valFiles($attribute, $params) {
        $val = $this->$attribute;
        
        if (! $this->hasErrors()) {
            if (empty($val['0'])) {
                $this->addError('file0', Yii::t('DadminModule.message', 'required_file', array(
                    '{0}' => 'Image',
                )));
            }
            if (empty($val['1'])) {
                $this->addError('file1', Yii::t('DadminModule.message', 'required_file', array(
                    '{0}' => 'Image',
                )));
            }
        }
    }
    /*-------------------------------------------------------------------------
      //VALIDATOR
     ------------------------------------------------------------------------*/
    
    /*-------------------------------------------------------------------------
      MISCELLANEOUS
     ------------------------------------------------------------------------*/
    public function clearSession() {
        $session = Yii::app()->user->getState($this->params['plupload_session']);
        $tempoDir = Yii::app()->params['tempo_dir'];
        
        if (isset($session['small'])) {
            @unlink($tempoDir . $session['small']['file_name']);
        }
        
        if (isset($session['normal'])) {
            @unlink($tempoDir . $session['normal']['file_name']);
            @unlink($tempoDir . $session['normal']['thumb_name']);
        }
        
        Yii::app()->user->setState($this->params['plupload_session'], null);
    }
    
    /**
     * @param string $file
     * @param array $cropInfo
     * @return string The name cropped file in Tempo directory
     */
    public function cropImage($file, $cropInfo, $session) {
        Yii::import('ext.wideImage.WideImage');
        $filePath = Yii::app()->params['tempo_dir'] . $file;
        $fileInfo = pathinfo($filePath);
        
        if (! isset($session['small'])) {
            $fileCropName = $fileInfo['filename'] . '_crop.' . $fileInfo['extension'];
        } else {
            $fileCropName = $session['small']['file_name'];
        }
        
        $fileCropPath = Yii::app()->params['tempo_dir'] . $fileCropName;
        
        $fileObj = WideImage::load($filePath);
        $fileObj->crop(
                round($cropInfo['x']), round($cropInfo['y']),
                round($cropInfo['w']), round($cropInfo['h'])
            )
        ->resize($this->params['small']['width'], $this->params['small']['height'])
        ->saveToFile($fileCropPath);
        
        return $fileCropName;
    }
    /*-------------------------------------------------------------------------
      //MISCELLANEOUS
     ------------------------------------------------------------------------*/
    
    /*-------------------------------------------------------------------------
      ONLY APPLY FOR UPDATING CASE
     ------------------------------------------------------------------------*/
    /**
     * Only apply in Update case.
     */
    public function setDefaultValue() {
        //set file1, file2
        $this->setAttribute('file1', 'had file');
        $this->setAttribute('file2', 'had file');
        
        $this->restoreSession();
    }
    
    public function restoreSession() {
        if (! Yii::app()->user->hasState($this->params['plupload_session'])) {
            //move file
            $tempDir = Yii::app()->params['tempo_dir'];
            $aFiles = explode(';', $this->files);

            copy($this->params['upload_dir'] . $aFiles['0'],
                $tempDir . $aFiles['0']
            );
            copy($this->params['upload_dir'] . $aFiles['1'],
                $tempDir . $aFiles['1']
            );
            copy($this->params['upload_dir'] . $aFiles['2'],
                $tempDir . $aFiles['2']
            );

            //write session
            Yii::app()->user->setState($this->params['plupload_session'], array(
                'normal' => array(
                    'file_name' => $aFiles['0'],
                    'thumb_name' => $aFiles['1'],
                ),
                'small' => array(
                    'file_name' => $aFiles['2'],
                    'thumb_name' => $aFiles['2'],
                ),
            ));
        }
    }
    /*-------------------------------------------------------------------------
      //ONLY APPLY FOR UPDATING CASE
     ------------------------------------------------------------------------*/
    
}